package pear.algorithm;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Dingo
 */
public class ReadWrite {

    private RandomAccessFile raf = null;
    private String path;

    public ReadWrite(String path) {
        this.path = path;
    }

    public long save(long offset, byte[] buffer) {
        try {
            if (offset == -1) {
                try {
                    offset = raf.length();
                } catch (IOException ex) {
                    Logger.getLogger(ReadWrite.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            raf.seek(offset);
            raf.write(buffer);
        } catch (IOException ex) {
            Logger.getLogger(ReadWrite.class.getName()).log(Level.SEVERE, null, ex);
        }
        return offset;
    }

    public boolean read(long offset, byte[] buffer) {
        try {
            raf.seek(offset);
            raf.readFully(buffer);
            return true;
        } catch (IOException ex) {
            Logger.getLogger(ReadWrite.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    }
    
    public long getLength(){
        try {
            return raf.length();
        } catch (IOException ex) {
            Logger.getLogger(ReadWrite.class.getName()).log(Level.SEVERE, null, ex);
        }
        return 0;
    }

    public void open() {
        try {
            raf = new RandomAccessFile(path, "rw");
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ReadWrite.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void close() {
        try {
            raf.close();
        } catch (IOException ex) {
            Logger.getLogger(ReadWrite.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
